package com.zhongan.gateway.filter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.zhongan.gateway.common.enums.GatewayErrorCodeEnum;
import com.zhongan.gateway.common.exception.GatewayException;
import com.zhongan.gateway.service.RedisService;

/**
 * 对ip流量进行控制
 */
@Component
public class OverFlowZuulFilter extends ZuulFilter {
    private Logger log = LoggerFactory.getLogger(OverFlowZuulFilter.class);
    //    private Counter overFlowControlCounter;
    @Resource
    private RedisService redisService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 13;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        log.info("进入检查参数filter");
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String overFlow = (String) request.getAttribute("overFlow");
        if (StringUtils.isEmpty(overFlow)) {
            return null;
        }
        //priviligeId+max
        String[] strs = overFlow.split("_");
        //        String key =  ;
        boolean count = redisService.overFlow(strs[0], Integer.parseInt(strs[1]));
        if (!count) {
            log.warn("filter: client[" + strs[0] + "], count[" + count + "]");
            request.setAttribute("gatewayException", new GatewayException(GatewayErrorCodeEnum.OVERFLOW.getCode(),
                    GatewayErrorCodeEnum.OVERFLOW.getMsg()));
            throw new RuntimeException();
        } else {
            log.info("filter: client[" + strs[0] + "], count[" + count + "]");
        }

        return null;
    }
}
